﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesOleDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AEFunction
{
    public class AEFunction
    {
        /// <summary>
        /// 填充DataTable中的数据
        /// </summary>
        /// <param name="pLayer"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static DataTable CreateDataTable(ILayer pLayer, string tableName)
        {
            IFeatureClass ipFClass = (pLayer as IFeatureLayer).FeatureClass;
            IDataset ipDataset = ipFClass as IDataset;
            IWorkspace ipWS = ipDataset.Workspace;
            IFDOToADOConnection fdoToadoConnection = new FdoAdoConnectionClass();

            ADODB.Connection adoConnection = new ADODB.Connection();

            fdoToadoConnection.Connect(ipWS, adoConnection);
            ADODB.Recordset adoRecordSet = new ADODB.Recordset();
            adoRecordSet.ActiveConnection = adoConnection;
            string sql = GetLayerSQL(pLayer);
            adoRecordSet.Open(sql, adoConnection, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic, 0);

            OleDbDataAdapter custDA = new OleDbDataAdapter();
            DataTable dtTerritories = new DataTable();
            custDA.Fill(dtTerritories, adoRecordSet);

            //FixShapeType(dtTerritories, GetLayerFeatureClass(pLayer).ShapeType;
            if (adoConnection.State == 1)
                adoConnection.Close();
            if (adoRecordSet.State == 1)
                adoRecordSet.Close();
            adoConnection = null;
            adoRecordSet = null;
            dtTerritories.Columns.Remove("Shape");
            return dtTerritories;
        }

        public static string GetLayerSQL(ILayer layer)
        {
            string sql = "select ";
            ITable pTable = layer as ITable;
            IField pField = null;
            //根据每个字段的属性建立DataColumn对象
            for (int i = 0; i < pTable.Fields.FieldCount; i++)
            {
                pField = pTable.Fields.get_Field(i);
                string field = pField.Name;
                //if (field == "Shape")
                //    field = "Geo;"
                if (i == pTable.Fields.FieldCount - 1)
                {
                    sql += field + "";
                }
                else
                {
                    sql += field + ",";
                }
            }
            sql += " from " + (layer as IFeatureLayer).FeatureClass.AliasName;
            return sql;
        }

        public static void CreateShapefile(string strShapeName, string strShapeFolder, esriGeometryType shapeFileType,
                                                                    ISpatialReference pSpatialReference , List<IField> fields)
        {
            if(pSpatialReference==null)
                pSpatialReference = new UnknownCoordinateSystemClass();
            IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(strShapeFolder, 0);

            //打开工作空间
            const string strShapeFieldName = "shape";
            //设置字段集
            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            //设置字段
            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            //创建类型为几何类型的字段
            pFieldEdit.Name_2 = strShapeFieldName;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

            //为esriFieldTypeGeometry类型的字段创建几何定义，包括类型和空间参照
            IGeometryDef pGeoDef = new GeometryDefClass();     //The geometry definition for the field if IsGeometry is TRUE.
            IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef;
            pGeoDefEdit.GeometryType_2 = shapeFileType;
            pGeoDefEdit.SpatialReference_2 = pSpatialReference;

            pFieldEdit.GeometryDef_2 = pGeoDef;
            pFieldsEdit.AddField(pField);

            foreach (IField f in fields)
            {
                pFieldsEdit.AddField(f);
            }
            //创建shapefile
            try
            {
                if (File.Exists(strShapeFolder + "\\" + strShapeName + ".shp"))
                {
                    MessageBox.Show("该shape文件已经存在，请重新命名。");
                    return;
                }
                pWS.CreateFeatureClass(strShapeName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, "");

                Marshal.ReleaseComObject(pFields);
                Marshal.ReleaseComObject(pFieldEdit);
                Marshal.ReleaseComObject(pGeoDef);
                Marshal.ReleaseComObject(pGeoDefEdit);
                Marshal.ReleaseComObject(pWSF);
                Marshal.ReleaseComObject(pWS);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }


}
